package org.jsola.hr.service.impl;

import org.jsola.common.DateKit;
import org.jsola.core.Page;
import org.jsola.hr.common.ExampleKit;
import org.jsola.hr.constant.HrConstants;
import org.jsola.hr.constant.ProgTypeEnum;
import org.jsola.hr.dao.IAttendanceMonthlyDAO;
import org.jsola.hr.dao.ISubsidyInfoDAO;
import org.jsola.hr.dao.ISubsidyProgDAO;
import org.jsola.hr.dto.*;
import org.jsola.hr.entity.*;
import org.jsola.hr.query.SubsidyProgQuery;
import org.jsola.hr.service.IApplyToProgService;
import org.jsola.hr.service.IEmpInfoService;
import org.jsola.hr.service.ISubsidyProgService;
import org.jsola.hr.vo.SubsidyProgListVO;
import org.jsola.hr.vo.SubsidyProgVO;
import org.jsola.user.core.TokenUser;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author zhr
 */
@Service("hrSubsidyProgServiceImpl")
public class SubsidyProgServiceImpl implements ISubsidyProgService {

    @Autowired
    private ISubsidyProgDAO subsidyProgDAO;

    @Autowired
    private ISubsidyInfoDAO subsidyInfoDAO;

    @Autowired
    private IApplyToProgService applyToProgService;

    @Autowired
    private IEmpInfoService empInfoService;

    @Autowired
    private IAttendanceMonthlyDAO attendanceMonthlyDAO;

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public SubsidyProgVO save(SubsidyProgAddDTO subsidyProgAddDTO, TokenUser tokenUser) {
        // 转DO
        SubsidyProgDO subsidyProgDO = subsidyProgAddDTO.to(SubsidyProgDO.class);
        // 保存
        subsidyProgDO = save(subsidyProgDO, tokenUser.getSiteId(), tokenUser.getUserId());
        return subsidyProgDO.to(SubsidyProgVO.class);
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public int update(SubsidyProgUpdateDTO subsidyProgUpdateDTO, TokenUser tokenUser) {
        //转DO
        SubsidyProgDO subsidyProgDO = subsidyProgUpdateDTO.to(SubsidyProgDO.class);
        //根据主键更新，只更新非null值
        return updateByIdSelective(subsidyProgDO, tokenUser.getSiteId(), tokenUser.getUserId());
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public int deleteByIds(TokenUser tokenUser, String... subsidyProgIds) {
        return logicalDeleteByIds(tokenUser.getSiteId(), tokenUser.getUserId(), (Object[]) subsidyProgIds);
    }


    @Override
    public SubsidyProgListVO selectById(String subsidyProgId, String siteId) {
        SubsidyProgListVO subsidyProgListVO = subsidyProgDAO.selectListWithChildById(subsidyProgId, siteId);
        if (subsidyProgListVO == null) {
            return null;
        }
        subsidyProgListVO.setApplyToProgVO(applyToProgService.selectByBusProgId(subsidyProgListVO.getId(), siteId));
        return subsidyProgListVO;
    }

    @Override
    public List<SubsidyProgListVO> select(SubsidyProgQuery subsidyProgQuery, String siteId) {
//        List<SubsidyProgDO> subsidyProgDOList = selectDO(subsidyProgQuery, siteId);
        List<SubsidyProgListVO> subsidyProgListVOList = subsidyProgDAO.selectListWithChild(subsidyProgQuery, siteId);
        if(CollectionUtils.isEmpty(subsidyProgListVOList)) {
            return subsidyProgListVOList == null ? null : new ArrayList<>();
        }
        subsidyProgListVOList.stream().map(subsidyProgListVO -> {
            subsidyProgListVO.setApplyToProgVO(applyToProgService.selectByBusProgId(subsidyProgListVO.getId(), siteId));
            return subsidyProgListVO;
        }).collect(Collectors.toList());
        return subsidyProgListVOList;
    }

    @Override
    public int selectCount(SubsidyProgQuery subsidyProgQuery, String siteId) {
        Example example = buildExample(subsidyProgQuery,siteId);
        return subsidyProgDAO.selectCountByExample(example);
    }

    @Override
    public Page<SubsidyProgListVO> selectPage(SubsidyProgQuery subsidyProgQuery, String siteId) {
        Example example = buildExample(subsidyProgQuery,siteId);
        Page<SubsidyProgDO> page = subsidyProgDAO.selectPageByExample(example,
                subsidyProgQuery.getPageNo(),
                subsidyProgQuery.getPageSize());

        return page.to(SubsidyProgListVO.class);
    }

    @Override
    public SubsidyProgDO selectDOById(String subsidyProgId, String siteId) {
        return listById(subsidyProgId, siteId);
    }

    @Override
    public List<SubsidyProgDO> selectDO(SubsidyProgQuery subsidyProgQuery, String siteId) {
        Example example = buildExample(subsidyProgQuery,siteId);
        return subsidyProgDAO.selectByExample(example);
    }


    /**
     * 根据查询参数，构建example

     * @param subsidyProgQuery 查询参数
     * @param siteId 所属站点id
     * @return example
     */
    private Example buildExample(SubsidyProgQuery subsidyProgQuery, String siteId) {
        Example example = new Example(SubsidyProgDO.class);
        example.and()
                .andEqualTo("valid", true)
                .andEqualTo("siteId", siteId);
        if (subsidyProgQuery.getName() != null) {
            example.and().andLike("name", "%" + subsidyProgQuery.getName() + "%");
        }
        if (subsidyProgQuery.getRemark() != null) {
            example.and().andLike("remark", "%" + subsidyProgQuery.getRemark() + "%");
        }
        if (subsidyProgQuery.getTaxMethod() != null) {
            example.and().andEqualTo("taxMethod", subsidyProgQuery.getTaxMethod());
        }
        if (subsidyProgQuery.getAttendanceRange() != null) {
            example.and().andEqualTo("attendanceRange", subsidyProgQuery.getAttendanceRange());
        }
        if (subsidyProgQuery.getAttendanceRangeDays() != null) {
            example.and().andEqualTo("attendanceRangeDays", subsidyProgQuery.getAttendanceRangeDays());
        }
        if (subsidyProgQuery.getCompanyId() != null) {
            example.and().andEqualTo("companyId", subsidyProgQuery.getCompanyId());
        }
        if (subsidyProgQuery.getGmtCreateStart() != null &&
                subsidyProgQuery.getGmtCreateEnd() != null) {
            example.and().andBetween("gmtCreate", subsidyProgQuery.getGmtCreateStart(),
                    subsidyProgQuery.getGmtCreateEnd());
        }
        if (subsidyProgQuery.getCreateUserId() != null) {
            example.and().andLike("createUserId", "%" + subsidyProgQuery.getCreateUserId() + "%");
        }
        if (subsidyProgQuery.getGmtModifiedStart() != null &&
                subsidyProgQuery.getGmtModifiedEnd() != null) {
            example.and().andBetween("gmtModified", subsidyProgQuery.getGmtModifiedStart(),
                    subsidyProgQuery.getGmtModifiedEnd());
        }
        if (subsidyProgQuery.getModifiedUserId() != null) {
            example.and().andLike("modifiedUserId", "%" + subsidyProgQuery.getModifiedUserId() + "%");
        }
        // 排序
        ExampleKit.setExampleOrder(example,subsidyProgQuery.getOrders());
        return example;
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public SubsidyProgVO addSubsidyProg(SubsidyProgAddDTO subsidyProgAddDTO, TokenUser tokenUser){
        // 转DO
        SubsidyProgDO subsidyProgDO = subsidyProgAddDTO.to(SubsidyProgDO.class);
        // 保存
        subsidyProgDO = save(subsidyProgDO, tokenUser.getSiteId(), tokenUser.getUserId());

        Date now = DateKit.getToday();
        SubsidyProgDO finalSubsidyProgDO = subsidyProgDO;
        subsidyProgAddDTO.getSubsidyInfoDOList().stream().map(subsidyInfoDO -> {
            subsidyInfoDO.setProgId(finalSubsidyProgDO.getId());
            subsidyInfoDO.setId(null);
            subsidyInfoDO.setSiteId(tokenUser.getSiteId());
            subsidyInfoDO.setValid(true);
            subsidyInfoDO.setCreateUserId(tokenUser.getUserId());
            subsidyInfoDO.setModifiedUserId(tokenUser.getUserId());
            subsidyInfoDO.setGmtCreate(now);
            subsidyInfoDO.setGmtModified(now);
            return subsidyInfoDO;
        }).collect(Collectors.toList());

        List<SubsidyInfoDO> subsidyInfoDOList = subsidyProgAddDTO.getSubsidyInfoDOList();
        //保存员工津贴配置信息列表
        if(!CollectionUtils.isEmpty(subsidyInfoDOList)){
            subsidyInfoDAO.insertListAndSetId(subsidyInfoDOList);
        }

        //保存方案适用设置
        ApplyToProgAddDTO applyToProgAddDTO = subsidyProgAddDTO.getApplyToProgAddDTO();
        applyToProgAddDTO.setBusProgType(ProgTypeEnum.SUBSIDY_PROG.getValue());
        applyToProgAddDTO.setBusProgId(subsidyProgDO.getId());
        applyToProgAddDTO.setMutex(false);
        applyToProgService.add(applyToProgAddDTO, tokenUser);

        SubsidyProgVO subsidyProgVO = subsidyProgDO.to(SubsidyProgVO.class);
        subsidyProgVO.setSubsidyInfoDOList(subsidyInfoDOList);
        return subsidyProgVO;
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public SubsidyProgVO updateSubsidyProg(SubsidyProgUpdateDTO subsidyProgUpdateDTO, TokenUser tokenUser){
        //转DO
        SubsidyProgDO subsidyProgDO = subsidyProgUpdateDTO.to(SubsidyProgDO.class);

        //删除员工津贴配置信息列表
        SubsidyInfoDO subsidyInfoDOTmp = new SubsidyInfoDO();
        subsidyInfoDOTmp.setProgId(subsidyProgDO.getId());
        subsidyInfoDOTmp.setSiteId(tokenUser.getSiteId());
        subsidyInfoDAO.delete(subsidyInfoDOTmp);

        Date now = DateKit.getToday();
        subsidyProgUpdateDTO.getSubsidyInfoDOList().stream().map(subsidyInfoDO -> {
            subsidyInfoDO.setProgId(subsidyProgDO.getId());
            subsidyInfoDO.setId(null);
            subsidyInfoDO.setSiteId(tokenUser.getSiteId());
            subsidyInfoDO.setValid(true);
            subsidyInfoDO.setCreateUserId(tokenUser.getUserId());
            subsidyInfoDO.setModifiedUserId(tokenUser.getUserId());
            subsidyInfoDO.setGmtCreate(now);
            subsidyInfoDO.setGmtModified(now);
            return subsidyInfoDO;
        }).collect(Collectors.toList());

        List<SubsidyInfoDO> subsidyInfoDOList = subsidyProgUpdateDTO.getSubsidyInfoDOList();
        //保存员工津贴配置信息列表
        if(!CollectionUtils.isEmpty(subsidyInfoDOList)){
            subsidyInfoDAO.insertListAndSetId(subsidyInfoDOList);
        }

        //根据主键更新，只更新非null值
        updateByIdSelective(subsidyProgDO, tokenUser.getSiteId(), tokenUser.getUserId());

        //保存方案适用设置
        ApplyToProgUpdateDTO applyToProgUpdateDTO = subsidyProgUpdateDTO.getApplyToProgUpdateDTO();
        applyToProgUpdateDTO.setBusProgType(ProgTypeEnum.SUBSIDY_PROG.getValue());
        applyToProgUpdateDTO.setBusProgId(subsidyProgDO.getId());
        applyToProgUpdateDTO.setMutex(false);
        applyToProgService.update(applyToProgUpdateDTO, tokenUser);

        SubsidyProgVO subsidyProgVO = subsidyProgDO.to(SubsidyProgVO.class);
        subsidyProgVO.setSubsidyInfoDOList(subsidyInfoDOList);
        return subsidyProgVO;
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public Boolean empSubsidyCount(TokenUser tokenUser, AttendanceMonthlyAddDTO attendanceMonthlyAddDTO){
        //获取员工列表
        EmpInfoDO empInfoDO = new EmpInfoDO();
        empInfoDO.setValid(true);
        empInfoDO.setCompanyId(attendanceMonthlyAddDTO.getCompanyId());
        List<EmpInfoDO> empInfoDOList = empInfoService.listWithSalary(empInfoDO, tokenUser.getSiteId());
        if(CollectionUtils.isEmpty(empInfoDOList)){
            return false;
        }

        // 获取津贴设置方案
        SubsidyProgDO subsidyProgDOTmp = new SubsidyProgDO();
        subsidyProgDOTmp.setValid(true);
        subsidyProgDOTmp.setSiteId(tokenUser.getSiteId());
        subsidyProgDOTmp.setCompanyId(attendanceMonthlyAddDTO.getCompanyId());
        List<SubsidyProgListVO> subsidyProgListVOList = progListWithItem(subsidyProgDOTmp, tokenUser.getSiteId());
        for (SubsidyProgListVO subsidyProgListVO : subsidyProgListVOList) {
            //获取津贴方案下员工列表
            ApplyToProgEmpeeInfoDTO applyToProgEmpeeInfoDTO = applyToProgService.getApplyToProgEmployeeByBusProgId(subsidyProgListVO.getId(), tokenUser.getSiteId(), attendanceMonthlyAddDTO.getCompanyId());
            if(Objects.isNull(applyToProgEmpeeInfoDTO)){
                continue;
            }

            //津贴设置方案适用员工集合
            List<String> empIdEmployList = applyToProgEmpeeInfoDTO.getEmpInfoDOList().stream().map(item -> item.getId()).collect(Collectors.toList());
            //员工列表和适用方案交集
            List<String> empIdList = empInfoDOList.stream().filter(item -> empIdEmployList.contains(item.getId())).map(item -> item.getId()).collect(Collectors.toList());
            //子项津贴金额
            List<SubsidyInfoDO> subsidyInfoDOList = subsidyProgListVO.getSubsidyInfoDOList();
            Integer amountSum = subsidyInfoDOList.stream().map(SubsidyInfoDO::getAmount).reduce(0, Integer::sum);

            //修改员工月考勤统计中的津贴金额
            if(CollectionUtils.isEmpty(empIdList)){
                continue;
            }
            AttendanceMonthlyDO attendanceMonthlyDO = new AttendanceMonthlyDO();
            attendanceMonthlyDO.setYear(attendanceMonthlyAddDTO.getYear());
            attendanceMonthlyDO.setMonth(attendanceMonthlyAddDTO.getMonth());
            attendanceMonthlyDO.setSiteId(tokenUser.getSiteId());
            attendanceMonthlyDO.setSubsidy(amountSum);
            attendanceMonthlyDO.setGmtModified(DateKit.getToday());
            attendanceMonthlyDO.setModifiedUserId(tokenUser.getUserId());
            attendanceMonthlyDAO.updateSubsidyByEmpIdList(attendanceMonthlyDO, empIdList);
        }
        return true;
    }

    private List<SubsidyProgListVO> progListWithItem(SubsidyProgDO subsidyProgDOTmp, String siteId) {
        SubsidyProgQuery subsidyProgQuery = new SubsidyProgQuery();
        BeanUtils.copyProperties(subsidyProgDOTmp, subsidyProgQuery);
        return subsidyProgDAO.selectListWithChild(subsidyProgQuery, siteId);
    }
}




